/* Copyright 2024 coremail
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { ModelBase } from '../model/mode_base';
import { SoapXmlWriter } from '../xml/soap_xml';
import { XmlAttribute } from '../xml/xml_attribute';
import { XmlElement } from '../xml/xml_element';
import { XmlNamespace } from '../xml/xml_namespace';

export abstract class RequestBase<T extends ModelBase> {
  constructor(protected rawData: T) {
  }

  protected abstract writeHeaderToXml(soapXmlWriter: SoapXmlWriter): void;

  protected abstract writeBodyToXml(soapXmlWriter: SoapXmlWriter): void;

  public writeToXml(soapXmlWriter: SoapXmlWriter): void {
    soapXmlWriter.writeStartDocument();

    // <soap:Envelope>
    soapXmlWriter.writeStartElement(XmlNamespace.SOAP, XmlElement.NAME_ENVELOPE)
      .writeAttrWithNamespace(XmlNamespace.XMLNS, XmlNamespace.XSI, XmlNamespace.SCHEMA_XSI)
      .writeAttrWithNamespace(XmlNamespace.XMLNS, XmlNamespace.MESSAGE, XmlNamespace.SCHEMA_MESSAGE)
      .writeAttrWithNamespace(XmlNamespace.XMLNS, XmlNamespace.TYPE, XmlNamespace.SCHEMA_TYPE)
      .writeAttrWithNamespace(XmlNamespace.XMLNS, XmlNamespace.SOAP, XmlNamespace.SCHEMA_SOAP);
    this.writeHeaderToXml(soapXmlWriter);
    this.writeBodyToXml(soapXmlWriter);

    // </soap:Envelope>
    soapXmlWriter.writeEndElement();
  }

  public xmlToString(soapXmlWriter: SoapXmlWriter): string {
    return soapXmlWriter.getXML();
  }

  protected writeCommonHeader(soapXmlWriter: SoapXmlWriter): void {
    soapXmlWriter.writeStartElement(XmlNamespace.SOAP, XmlElement.NAME_HEADER);
    soapXmlWriter.writeElementWithAttribute(XmlNamespace.TYPE, XmlElement.NAME_REQUEST_SERVER_VERSION,
      new Map([[XmlAttribute.NAME_VERSION, this.rawData.getRequestServiceVersion()]]));
    soapXmlWriter.writeEndElement();
  }
}

